package com.example.javapoint.sync.block;

/**
 * 静态方法同步 -> 内部类实现
 * 存在的意义：假设有线程t1 t2 操作Table 的实例对象obj1, 线程t3 t4操作Table 的实例对象obj2
 * 如果仅使用同步的方法t1 t3, t2 t4 可能存在问题, 所以需要解决同步问题就会涉及到静态同步
 */

class Table2 {
    synchronized static void print(int n) {
        for (int i = 1; i < 10; i++) {
            System.out.println(i * n);
            try {
                Thread.sleep(400);
            } catch (InterruptedException e) {
                System.out.println("Thread is interrupted");
            }
        }
    }
}

/**
 * 同步代码块解决多线程访问同一资源问题
 */
class Table3 {
    static void print(int n) {
       synchronized (Table3.class){
           for (int i = 1; i < 10; i++) {
               System.out.println(i * n);
               try {
                   Thread.sleep(400);
               } catch (InterruptedException e) {
                   System.out.println("Thread is interrupted");
               }
           }
       }
    }
}

public class TestStaticSync2 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            //Table2.print(1);
            Table3.print(1);
        });
        Thread t2 = new Thread(() -> {
            //Table2.print(10);
            Table3.print(10);
        });
        Thread t3 = new Thread(() -> {
            //Table2.print(100);
            Table3.print(100);
        });
        Thread t4 = new Thread(() -> {
            //Table2.print(1000);
            Table3.print(1000);
        });

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
